package com.iot.service.mqtt.retry;

import com.iot.service.mqtt.config.TlSessionProperties;
import com.iot.service.mqtt.utils.ChannelManager;
import io.netty.channel.Channel;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hszhou
 * @Date: 2025/5/7 9:56
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
@RequiredArgsConstructor
public class TlRetryServiceImpl extends HashedWheelTimer implements RetryStrategy {

    private final ChannelManager channelManager;

    private final TlSessionProperties sessionProperties;


    public ConcurrentHashMap<String, TlRetryTask> map = new ConcurrentHashMap<>();
    @Override
    public void retry(TlRetryMessage req, String clientId) {

        Channel channel = channelManager.getChannel(clientId);
        if(channel!=null && channel.isActive()){
            TlRetryTask retryTask = new TlRetryTask(req, channel, sessionProperties.getDelay());
            Timeout timeout = this.newTimeout(retryTask, sessionProperties.getDelay(), TimeUnit.SECONDS);
            retryTask.setTimeout(timeout);
            map.put(req.getMessageId().toString(),retryTask);
        }

    }

    @Override
    public void cancel(Long messageId) {
        String msgId = messageId.toString();
        TlRetryTask tlRetryTask = map.get(msgId);
        if(tlRetryTask!=null){
            tlRetryTask.cancel();
            map.remove(msgId);
        }
    }

    @Override
    public void removeSession(String clientId) {

    }
}
